
import javax.microedition.location.Criteria;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationProvider;

public class ConfigurationProvider {
	private static ConfigurationProvider INSTANCE = null;
	private static Criteria[] freeCriterias = null;
	private static String[] freeCriteriaNames = null;
	private static Criteria[] costCriterias = null;
	private static Criteria[] costCriteriaNames = null;
	private ProviderQueryUI queryUI = null;
	private Criteria criteria = null;
	private LocationProvider provider = null;
	static{
		
		freeCriterias = new Criteria[2];
		freeCriteriaNames = new String[2];
		
		Criteria crit1 = new Criteria();
		crit1.setHorizontalAccuracy(25); // 25m 
		crit1.setVerticalAccuracy(25); // 25m 
		crit1.setPreferredResponseTime(Criteria.NO_REQUIREMENT); 
		crit1.setPreferredPowerConsumption(Criteria.NO_REQUIREMENT); 
		crit1.setCostAllowed(false); 
		crit1.setSpeedAndCourseRequired(true); 
		crit1.setAltitudeRequired(true); 
		crit1.setAddressInfoRequired(true);  
		
		freeCriterias[0] = crit1;
		freeCriteriaNames[0] = "High details, cost not allowed";
		
		Criteria crit2 = new Criteria();
		
		crit2.setHorizontalAccuracy(Criteria.NO_REQUIREMENT); 
		crit2.setVerticalAccuracy(Criteria.NO_REQUIREMENT);  
		crit2.setPreferredResponseTime(Criteria.NO_REQUIREMENT); 
		crit2.setPreferredPowerConsumption(Criteria.NO_REQUIREMENT); 
		crit2.setCostAllowed(false); 
		crit2.setSpeedAndCourseRequired(false); 
		crit2.setAltitudeRequired(false); 
		crit2.setAddressInfoRequired(false);  
		
		freeCriterias[1] = crit2;
		freeCriteriaNames[1] = "Low details and power consumption, cost not allowed";
		
	}
	private ConfigurationProvider(){
		queryUI = new ProviderQueryUI();
	}
	public static ConfigurationProvider getInstance(){
		if(INSTANCE == null){
			INSTANCE = new ConfigurationProvider();
		}
		else{
			//INSTANCE = null;
		}
		return INSTANCE;
	}
	
	public static boolean isLocationApiSupported(){
		String version = System.getProperty("microedition.location.version");
		return(version != null && !version.equals(""))? true : false;
	}
	
	public LocationProvider getSelectedProvider(){
		return provider;
	}
	
	public void autoSearch(ProviderStatusListener listener) {
		try{
			for(int i = 0; i< freeCriterias.length; i++){
				criteria = freeCriterias[i];
				provider = LocationProvider.getInstance(criteria);
				if(provider != null){
					listener.providerSelectedEvent();
					return;
				}
			}
			queryUI.showNoFreeServiceFound();
		}catch
 (LocationException le) { queryUI.showOutOfService();
			}
		}
}